package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.query.NewsQueryObject;
import cn.wolfcode.trip.base.service.INewsService;
import cn.wolfcode.trip.base.service.INewsTypeService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private INewsService newsService;
    @Autowired
    private INewsTypeService typeService;
    @Autowired
    private IUserService userService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") NewsQueryObject qo, Model model){
        //
        qo.setOrderBy("n.releaseTime desc");
        model.addAttribute("result", newsService.query(qo));
        model.addAttribute("types", typeService.list());
        return "news/list";
    }

   @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(News entity, MultipartFile img){
        //先处理上传图片的问题
        if (img != null && img.getContentType().startsWith("image") && img.getSize() > 0){
            //把图片上传到本地图库
            String url = UploadUtil.upload(img);
            //替换旧的图片地址
            entity.setCoverUrl(url);
        }
        newsService.saveOrUpdate(entity);
        return "redirect:/news/list.do";
    }

    @RequestMapping("/changeIsReleaseBtn")
    @ResponseBody
    public Object changeIsReleaseBtn(Long id, Integer isRelease){
        newsService.changeStateBtn(id, isRelease);
        return new JSONResult();
    }

    @RequestMapping(value = "/getContentById", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getContentById(Long id){
        return newsService.getContentById(id);
    }


}
